package com.example.deepseek.controller;

import com.example.deepseek.model.ChatSession;
import com.example.deepseek.model.Message;
import com.example.deepseek.service.DeepseekService;
import com.example.deepseek.utils.MessageFormatterHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

@Controller
@Slf4j
@RequiredArgsConstructor
public class ChatController {

    private final DeepseekService deepseekService;

    private final MessageFormatterHelper messageFormatterHelper;

    @GetMapping("/")
    public String index(Model model) {
        List<ChatSession> chatSessions = deepseekService.getAllSessions();

        if (chatSessions.isEmpty()) {
            // Create a default session if none exists
            ChatSession defaultSession = deepseekService.createChatSession("New Chat");
            model.addAttribute("currentSession", defaultSession);
        } else {
            model.addAttribute("currentSession", chatSessions.get(0));
        }

        model.addAttribute("chatSessions", chatSessions);
        model.addAttribute("messageFormatter", messageFormatterHelper);  // 添加到模型
        return "index";
    }

    @GetMapping("/chat/{sessionId}")
    public String chatSession(@PathVariable String sessionId, Model model) {
        ChatSession chatSession = deepseekService.getSession(sessionId);

        if (chatSession == null) {
            return "redirect:/";
        }

        model.addAttribute("currentSession", chatSession);
        model.addAttribute("chatSessions", deepseekService.getAllSessions());
        model.addAttribute("messageFormatter", messageFormatterHelper);  // 添加到模型
        return "index";
    }

    @PostMapping("/chat/new")
    public String newChat(@RequestParam(required = false) String name) {
        String sessionName = name != null && !name.trim().isEmpty() ? name : "New Chat";
        ChatSession session = deepseekService.createChatSession(sessionName);
        return "redirect:/chat/" + session.getId();
    }

    @PostMapping("/api/chat/{sessionId}/send")
    @ResponseBody
    public ResponseEntity<Message> sendMessage(
            @PathVariable String sessionId,
            @RequestParam String message) {
        try {
            Message response = deepseekService.sendMessage(sessionId, message).get();
            return ResponseEntity.ok(response);
        } catch (InterruptedException | ExecutionException e) {
            log.error("Error sending message", e);
            return ResponseEntity.badRequest().body(new Message("error", e.getMessage()));
        }
    }

    @MessageMapping("/chat.sendMessage")
    @SendTo("/topic/public")
    public Message sendMessageWebsocket(@Payload Message message) {
        return message;
    }

    // 添加到ChatController.java类中

    /**
     * 重命名会话
     */
    @PostMapping("/api/chat/{sessionId}/rename")
    @ResponseBody
    public ResponseEntity<Map<String, String>> renameChat(
            @PathVariable String sessionId,
            @RequestParam String name) {

        Map<String, String> response = new HashMap<>();

        try {
            ChatSession session = deepseekService.getSession(sessionId);

            if (session == null) {
                response.put("error", "会话不存在");
                return ResponseEntity.badRequest().body(response);
            }

            // 更新会话名称
            session.setName(name);
            deepseekService.updateSession(session);

            response.put("status", "success");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("重命名会话失败", e);
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/api/chat/{sessionId}/clear")
    @ResponseBody
    public ResponseEntity<Map<String, String>> clearChat(@PathVariable String sessionId) {
        Map<String, String> response = new HashMap<>();

        try {
            deepseekService.clearSession(sessionId);
            response.put("status", "success");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("清空对话失败", e);
            response.put("error", "清空对话失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @DeleteMapping("/api/chat/{sessionId}")
    @ResponseBody
    public ResponseEntity<Map<String, String>> deleteChat(@PathVariable String sessionId) {
        Map<String, String> response = new HashMap<>();

        try {
            deepseekService.deleteSession(sessionId);
            response.put("status", "success");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除会话失败", e);
            response.put("error", "删除会话失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }


}